package com.tencent.albert.weixin.driver.dao;

import com.tencent.albert.weixin.driver.bean.AccessToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;

/**
 * Created by albertzhu on 15/2/13.
 */
public class AccessTokenDao extends BaseDao{

    private static Logger logger = LoggerFactory.getLogger(AccessTokenDao.class);

    public AccessToken getAccessToken(long id ) {
        String sql = "";
        if (id == 0) {
            sql = "select * from access_Tokens order by id desc limit 0,1  ";
        } else {
            sql = "select * from access_Tokens where id = "+id;
        }
        Connection con = getConn();
        Statement st = null;
        ResultSet rs = null;
        AccessToken token = null;
        try {
            st = con.createStatement();
            rs = st.executeQuery(sql);
            while (rs.next()) {
                token = new AccessToken();
                token.setExpires_In(rs.getInt("expiresIn"));
                token.setId(rs.getLong("id"));
                token.setAccess_Token(rs.getString("token"));
                token.setCreate_at(rs.getTimestamp("created_at"));
                token.setUpdate_at(rs.getTimestamp("updated_at"));
            }
            if (null != token) {
                logger.info("get accessToken from db");
            }
        } catch(Exception e) {
            logger.info("get accessToken error "+e,e);
        } finally {
            closeConn(rs,st,con);
        }
        return token;
    }

    public void updateAccessToken(AccessToken token) {
        AccessToken oldToken = getAccessToken(token.getId());
        String sql = "";
        if (null == oldToken ) {
            sql = "insert into access_Tokens (`token`, `expiresIn`, `created_at`, `updated_at`) values (?,?,?,?) ";
        } else {
            sql = "update access_Tokens set `token` = ? , `expiresIn` = ? , `updated_at` = ? where `id` = ?";
        }
        Connection con = getConn();
        PreparedStatement pstmt = null;
        try {
            pstmt=con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
            pstmt.setString(1, token.getAccess_Token());
            pstmt.setInt(2, token.getExpires_In());
            long now = (new java.util.Date()).getTime();
            if (null == oldToken) {
                pstmt.setTimestamp(3, new java.sql.Timestamp(now));
                pstmt.setTimestamp(4, new java.sql.Timestamp(now));
            } else {
                pstmt.setTimestamp(3, new java.sql.Timestamp(now));
                pstmt.setLong(4, token.getId());
            }
            pstmt.execute();
            if (null == oldToken) {
                ResultSet rs = pstmt.getGeneratedKeys(); //获取结果
                if (rs.next()) {
                    token.setId(rs.getLong(1));
                }
                rs.close();
            }
            logger.info("updateAccessToken set token , id is "+token.getId());
        } catch(Exception e) {
            logger.info("get accessToken error "+e,e);
        } finally {
            closeConn(pstmt,con);
        }
    }


}
